<template>
  <div>
    <h2>各场馆排班次数报表</h2>
    <div :class="className" :style="{ height: height, width: width }" />
  </div>
</template>

<script>
import * as echarts from 'echarts';
import resize from '@/views/dashboard/mixins/resize';
import { countSchedule } from '@/api/hj/venues';

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '400px',
    },
  },
  data() {
    return {
      chart: null,
      chartLoading: false, // 新增加载状态
      chartData: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.chartLoading = true; // 开始加载数据
      this.initChartWithData();
    });
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    // 获取数据并初始化图表
    async initChartWithData() {
      try {
        const response = await countSchedule(); // 假设这是一个返回Promise的异步函数
        if (Array.isArray(response.data)) {
          this.chartData = response.data.map(item => ({
            name: item.venueName,
            value: item.scheduleCount,
          }));
          this.initChart();
        } else {
          console.error('Invalid data format received:', response.data);
          this.handleChartError('Received invalid data format.');
        }
      } catch (error) {
        console.error('Failed to fetch chart data:', error);
        this.handleChartError('Failed to load chart data.');
      } finally {
        this.chartLoading = false; // 结束加载数据
      }
    },
    // 初始化图表的方法
    initChart() {
      if (!this.chartData.length) return;

      this.chart = echarts.init(this.$el.querySelector('.chart'), 'macarons');
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c}',
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: this.chartData.map(item => item.name),
        },
        series: [
          {
            name: 'Venue Schedule Counts',
            type: 'pie',
            roseType: 'radius',
            radius: ['15%', '75%'],
            center: ['50%', '42%'],
            data: this.chartData,
            animationEasing: 'cubicInOut',
            animationDuration: 1500,
          },
        ],
      });

      window.addEventListener('resize', this.handleResize); // 确保图表在窗口大小变化时能够自适应
    },
    // 处理图表加载错误的函数
    handleChartError(message) {
      // 这里可以添加错误处理的逻辑，比如显示错误消息或使用静态数据
      console.error('Chart error:', message);
      // 可以考虑显示一个错误提示组件或简单的错误提示信息
      // 例如：this.$alert(message, 'Chart Error', { dangerouslyUseHTMLString: true });
    },
    // 窗口大小变化时处理图表自适应
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize); // 组件销毁前移除事件监听器
  },
};
</script>

<style scoped>
/* 可以在这里添加组件的样式 */
</style>